package com.example.demo.gateway.controller;

import com.example.demo.gateway.entity.GatewayRoute;
import com.example.demo.gateway.req.GatewayRouteReq;
import com.example.demo.gateway.service.GatewayRouteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.validation.Valid;

@Slf4j
@RestController
@RequestMapping("/gateway/route")
public class GatewayRouteController {

    @Autowired
    private GatewayRouteService gatewayRouteService;

    @GetMapping("/list")
    public Flux<GatewayRoute> findAll() {
        return gatewayRouteService.findAll();
    }

    @GetMapping("/{id}")
    public Mono<GatewayRoute> findById(@PathVariable Long id) {
        return gatewayRouteService.findById(id);
    }

    @PostMapping("/")
    public Mono<GatewayRoute> add(@Valid  @RequestBody GatewayRouteReq gatewayRouteReq) {
        //参数校验
        return gatewayRouteService.findByRname(gatewayRouteReq.getRname())
                .map(gr -> {
                    log.error(gr.toString());
                    throw new RuntimeException("路由名称已存在");
                })
                .then(gatewayRouteService.add(gatewayRouteReq));
    }

    @PutMapping("/{id}")
    public Mono<GatewayRoute> update(@PathVariable Long id, @RequestBody GatewayRouteReq gatewayRouteReq) {
        gatewayRouteReq.setId(id);
        log.info("正在保存");
        return gatewayRouteService.update(gatewayRouteReq);
    }
    @DeleteMapping("/delete/{id}")
    public Mono<ResponseEntity<Void>> delete(@PathVariable Long id) {
        return gatewayRouteService.deleteById(id);
    }

    @GetMapping("/page")
    public Flux<GatewayRoute> findPage(Integer pageNo, Integer pageSize) {
        return gatewayRouteService.findPage(pageNo, pageSize);
    }
    @GetMapping("/count")
    public Mono<Long> findCount() {
        return gatewayRouteService.count();
    }
}
